package com.fingard.dsp;

import java.io.File;

import com.fingard.FGBiz;
import com.fingard.dsp.distribute.bocom12.BOCOM12Listener;
import com.fingard.dsp.distribute.dstrbset.DstrbItem;
import com.fingard.dsp.distribute.payfree01.PAYFREE01Listener;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

public class Distributor {
	public String rootDirPath = "";
	public String logsDirPath = "";
	
	public Distributor(String p_mainDir){
		rootDirPath = StringHelper.trimEnd(p_mainDir,File.separator);
		logsDirPath = rootDirPath;
	}
	
	public void init() throws Exception{
		String tmpFileName = rootDirPath+File.separator+ "config"+File.separator + "Distributor.xml";
		File tmpFile = new File(tmpFileName);
		String strDstrbConfig ="";
		if(tmpFile.exists()){
			 strDstrbConfig = FileHelper.readToString(tmpFile, "utf-8");
		}
		else if(FGBiz.dspCenter != null && FGBiz.dspCenter.dspConfig != null){
			boolean enableDbConfig = FGBiz.dspCenter.dspConfig.getValueAsBool("enableDbConfig");
			if(enableDbConfig && FGBiz.dspCenter.dspSet.dbConnectionSet != null){
		     strDstrbConfig = XmlHander.dbtoxml("Distributor.xml",FGBiz.dspCenter.dspSet.dbConnectionSet.getConnection(),"config");
			}
		}
		if(strDstrbConfig==null||"".equals(strDstrbConfig)){
			return;
		}
	    XmlTextReader xmlReader = new XmlTextReader(strDstrbConfig);
	    String logDir = xmlReader.getFirstText("/config/logsDirPath");
	    if(StringHelper.hasAnyChar(logDir)){
	    	logsDirPath = StringHelper.trimEnd(logDir, File.separator);
	    }
	    while(xmlReader.read("/config/dstrbItem")){
	    	
	    	boolean enable = xmlReader.readedXElement.getAttrValueAsBool("enable");
	    	if(enable){
	    		DstrbItem eachItem = new DstrbItem();
		    	eachItem.fromXElement(xmlReader.readedXElement);
		    	//开一个线程去处理
		    	if(eachItem.dstrbCode.equals("BOCOM12")){
		    		if(eachItem.portForDSP.length()>0){
		    			BOCOM12Listener eachThread1 = new BOCOM12Listener(eachItem, 1, 1);
		    			new Thread(eachThread1).start();
		    		}
		    		if(eachItem.filePortForDSP.length()>0){
		    			BOCOM12Listener eachThread2 = new BOCOM12Listener(eachItem, 1, 2);
		    			new Thread(eachThread2).start();
		    		}
		    		if(eachItem.portForBank.length()>0){
		    			BOCOM12Listener eachThread3 = new BOCOM12Listener(eachItem, 2, 1);
		    			new Thread(eachThread3).start();
		    		}
		    		if(eachItem.filePortForBank.length()>0){
		    			BOCOM12Listener eachThread4 = new BOCOM12Listener(eachItem, 2, 2);
		    			new Thread(eachThread4).start();
		    		}
		    	}
		    	else if(eachItem.dstrbCode.equals("PAYFREE01")){
		    		if(eachItem.portForBank.length()>0){
		    			PAYFREE01Listener eachThread1 = new PAYFREE01Listener(eachItem, 2, 1);
		    			new Thread(eachThread1).start();
		    		}
		    	}
	    	}
	    }
	}
}
